<?php
declare (strict_types = 1);

namespace app\wework\controller\user\group;

use think\facade\Db;
use think\facade\Session;
use app\wework\controller\Base;
use app\wework\model\BaseModel;
use think\facade\Log;
use app\wework\model\user\group\GroupModel;
use app\wework\model\QyWechatApi;
include "../extend/PHPExcel/php-excel.class.php";

/**
* 群管理
**/
class Group extends Base 
{
	/**
     * 客户群列表
     * @return
     */
	public function index(){
		$wid = Session::get('wid');
		$staff = $this->req->param("staff");
		$name = $this->req->param("name");
		$tags = $this->req->param("tags");
		$status = $this->req->param("status");
		$order = $this->req->param("order")?:"desc";
		$times = $this->req->param("times");
		$page = $this->req->param("page")?:1;
		$size = $this->req->param("size")?:10;
		$res = GroupModel::list($page,$size,$staff,$name,$tags,$status,$order,$times);

		return success('客户群列表',$res);
	}


    //导出Excel
    public function downexcel(){
        $wid = $this->req->param("wid");
        $staff = $this->req->param("staff");
        if($staff)$staff = explode(",",$staff);
        $name = $this->req->param("name");
        $tags = $this->req->param("tags");
        if($tags)$tags = explode(",",$tags);
        $status = $this->req->param("status");
        $order = $this->req->param("order")?:"desc";
        $times = $this->req->param("times");
        $page = $this->req->param("page")?:1;
        $size = $this->req->param("size")?:10;
        $res = GroupModel::list($page,$size,$staff,$name,$tags,$status,$order,$times,$wid);
        $arr = [
           0 => []
        ];
        $i = 1;
        foreach($res["item"] as $value){
            $arr[$i]["客户群名称"] = $value["name"];
            $arr[$i]["群主名称"] = $value["staff"]["name"];
            $arr[$i]["群主所在部门"] = implode(",",$value["staff"]["department"]);
            $arr[$i]["群标签"] = implode(",",array_column($value["tags"], "name"));
            $arr[$i]["群人数"] = $value["size"];
            $arr[$i]["当日入群"] = $value["day_add"];
            $arr[$i]["当日退群"] = $value["day_del"];
            $arr[$i]["创建时间"] = $value["create_time"];
            $arr[$i]["群ID"] = $value["chat_id"];
            $i++;
        }
        $str = "渠道活码数据统计-列表数据";
        $xls = new \Excel_XML('utf-8', false, '数据导出');
        $xls->addArray($arr);
        $xls->generateXML($str.date('Y-m-d H:i:s'),time());
        exit();
    }


	/**
     * 客户群列表
     * @return
     */
	public function detail(){
		$chatId = $this->req->param('chat_id');
		$res = GroupModel::detail($chatId);

		return success('群详情',$res);
	}

	/*
	* 详情拉取 图表数据
	* type 1为总数量，2为客户总数，3为入群人数，4为流失人数
	*/
	public function detailMap(){
		$chatId = $this->req->param('chat_id');
		$type = $this->req->param('type');
		if(!$chatId || !$type)return error("参数错误");
		$group = GroupModel::group($chatId);
		$ktime = $this->req->param('ktime')?:date("Y-m-d",time()-3600*24*7);
		$dtime = $this->req->param('dtime')?:date("Y-m-d",time()-3600*24);
		if($ktime < date("Y-m-d",$group["create_time"]))$ktime = date("Y-m-d",$group["create_time"]);
		if(date("Y-m-d") <= $dtime)return error("时间超限");
		$time = strtotime($dtime) - strtotime($ktime);
		$time_tow = $ktime;
		$data = [];
		for ($i=0;$i<=$time/(3600*24);$i++){
			$time_one = date("Y-m-d",strtotime($time_tow));
			$time_tow = date("Y-m-d",strtotime($time_tow)+3600*24);
			$data[$i]["time"] = $time_one;
			if($type == 1)$data[$i]["size"] = GroupModel::groupSize($chatId,$time_tow);
			if($type == 2)$data[$i]["size"] = GroupModel::clientSize($chatId,$time_tow);
			if($type == 3)$data[$i]["size"] = GroupModel::addSize($chatId,$time_one,$time_tow);
			if($type == 4)$data[$i]["size"] = GroupModel::delSize($chatId,$time_one,$time_tow);
		}

		return success("获取成功",$data);
	}
	/**
     * 同步客户群
     * @return
     */
	public function sync(){
		$wid = Session::get('wid');
		$list = QyWechatApi::getExternalGroupchatList();
		if(!$list) return error('同步失败');
		$mh = curl_multi_init();
        $conn = [];
        $res = [];
        $url = $this->req->domain()."/wework/user/group/groupsync";
        for ($i=0;$i<count($list);$i++) {
            $data = http_build_query(["chat"=>$list[$i],"wid"=>$wid]);
            $conn[$i]=curl_init($url);
            curl_setopt($conn[$i],CURLOPT_RETURNTRANSFER,1); //如果成功只将结果返回，不自动输出任何内容
            curl_setopt($conn[$i],CURLOPT_TIMEOUT,0);
            curl_setopt($conn[$i], CURLOPT_POSTFIELDS, $data); //post 传参
            curl_multi_add_handle ($mh,$conn[$i]);
        }
        do { $n=curl_multi_exec($mh,$active); }
        while ($active);
        $result = true;
        for ($i=0;$i<count($list);$i++) {
            $res[$i]=curl_multi_getcontent($conn[$i]);
            curl_close($conn[$i]);
            if($res[$i] != 1){
                $result = false;
            }
        }

        return success("同步成功");
	}

	public function chatSync(){
		$wid = Session::get("wid");
		$chat_id = $this->req->param('chat_id');
		$res = QyWechatApi::getExternalGroupchatDetail($chat_id,$wid);
        if($res['errcode'] != 0) return error("错误",$res["errcode"]);
        $group_chat = $res['group_chat'];
        $group = Db::table('kt_wework_group')->where('wid',$wid)->where('chat_id',$chat_id)->find();
        $groupData = [];
        if($group) $groupData['id'] = $group['id'];
        $groupData['wid'] = $wid;
        $groupData['chat_id'] = $chat_id;
        $groupData['name'] = $group_chat['name']?:'默认群名';
        $staffid = Db::table('kt_wework_staff')->where('wid',$wid)->where('userid',$group_chat['owner'])->value('id');
        $groupData['staff_id'] = $staffid;
        $groupData['owner'] = $group_chat['owner'];
        if(isset($group_chat['notice']))$groupData['notice'] = json_encode($group_chat['notice']);
        $groupData['create_time'] = $group_chat['create_time'];
        $groupData['admin'] = $group_chat['admin_list'];
        Db::table('kt_wework_group')->json(['admin'])->save($groupData);
        $memberData = array_map(function($member)use($wid,$chat_id){
            $arr = [
                'wid'=>$wid,
                'chat_id'=>$chat_id,
                'userid'=>$member['userid'],
                'type'=>$member['type'],
                'join_time'=>$member['join_time'],
                'join_scene'=>$member['join_scene'],
                'unionid'=>$member['unionid']??'',
                'group_nickname'=>json_encode($member['group_nickname']),
                'name'=>filterEmoji($member['name'])
            ];
            if(isset($member["invitor"]))$arr["invitor"] = $member["invitor"];
            if(!isset($member["invitor"]))$arr["invitor"] = [];
            return $arr;
        }, $group_chat['member_list']);
        $sql = '';
        $sql = Db::table('kt_wework_group_member')->json(['invitor'])->fetchSql(true)->insertAll($memberData);
        $sql .= ' ON DUPLICATE KEY UPDATE group_nickname=VALUES(group_nickname),`name`=VALUES(`name`),unionid=VALUES(unionid)';
        Db::execute($sql);

        return success("操作成功");
	}

	public function syncGroup(){
        $chat = $_POST["chat"];
        $wid = $_POST["wid"];
        $res = QyWechatApi::getExternalGroupchatDetail($chat["chat_id"],$wid);
        if($res['errcode'] != 0) return error("错误",$res["errcode"]);
        $group_chat = $res['group_chat'];
        $group = Db::table('kt_wework_group')->where('wid',$wid)->where('chat_id',$chat['chat_id'])->find();
        $groupData = [];
        if($group) $groupData['id'] = $group['id'];
        $groupData['wid'] = $wid;
        $groupData['chat_id'] = $chat['chat_id'];
        $groupData['status'] = $chat['status'];
        $groupData['name'] = $group_chat['name']?:'默认群名';
        $staffid = Db::table('kt_wework_staff')->where('wid',$wid)->where('userid',$group_chat['owner'])->value('id');
        $groupData['staff_id'] = $staffid;
        $groupData['owner'] = $group_chat['owner'];
        if(isset($group_chat['notice']))$groupData['notice'] = json_encode($group_chat['notice']);
        $groupData['create_time'] = $group_chat['create_time'];
        $groupData['admin'] = $group_chat['admin_list'];
        Db::table('kt_wework_group')->json(['admin'])->save($groupData);
        $memberData = array_map(function($member)use($wid,$chat){
            $arr = [
                'wid'=>$wid,
                'chat_id'=>$chat['chat_id'],
                'userid'=>$member['userid'],
                'type'=>$member['type'],
                'join_time'=>$member['join_time'],
                'join_scene'=>$member['join_scene'],
                'unionid'=>$member['unionid']??'',
                'group_nickname'=>json_encode($member['group_nickname']),
                'name'=>filterEmoji($member['name'])
            ];
            if(isset($member["invitor"]))$arr["invitor"] = $member["invitor"];
            if(!isset($member["invitor"]))$arr["invitor"] = [];
            return $arr;
        }, $group_chat['member_list']);
        $sql = '';
        $sql = Db::table('kt_wework_group_member')->json(['invitor'])->fetchSql(true)->insertAll($memberData);
        $sql .= ' ON DUPLICATE KEY UPDATE group_nickname=VALUES(group_nickname),`name`=VALUES(`name`),unionid=VALUES(unionid)';
        $res = Db::execute($sql);
        
        return success("操作成功");
    }

	/**
	* 客户群成员详情数据
	*/
	public function detailClient(){
		$page = $this->req->param("page")?:1;
		$size = $this->req->param("size")?:10;
		$name = $this->req->param('name');
		$type = $this->req->param('type');
		$chatId = $this->req->param('chat_id');
		if(!$chatId || !$type)return error("参数错误");
		$group = GroupModel::group($chatId);
		$ktime = $this->req->param('ktime')?:date("Y-m-d",time()-3600*24*7);
		$dtime = $this->req->param('dtime')?:date("Y-m-d",time()-3600*24);
		if($type == 1)$data = GroupModel::detailClient($chatId,$page,$size,$name);
		if($type == 2){
            if($ktime < date("Y-m-d",$group["create_time"]))$ktime = date("Y-m-d",$group["create_time"]);
			if(date("Y-m-d") <= $dtime)return error("时间超限");
			$time = strtotime($dtime) - strtotime($ktime);
			$time_tow = $ktime;
			$data = [];
			for ($i=0;$i<=$time/(3600*24);$i++){
				$time_one = date("Y-m-d",strtotime($time_tow));
				$time_tow = date("Y-m-d",strtotime($time_tow)+3600*24);
				$data[$i]["time"] = $time_one;
				$data[$i]["size"] = GroupModel::groupSize($chatId,$time_tow);
				$data[$i]["add_size"] = GroupModel::addSize($chatId,$time_one,$time_tow);
				$data[$i]["del_size"] = GroupModel::delSize($chatId,$time_one,$time_tow);
			}
		}
		
		return success('群详情',$data);
	}


	/*
	* 批量打标签
	*/
	public function batchTag(){
		$chatIds = $this->req->param('chatIds');
		$tags = $this->req->param('tags');
		if(!$tags || !$chatIds)return error("参数错误");
        $tag_info = [];
        foreach($tags as $value){
            $tag_info[] = strval($value);
        }
		$res = GroupModel::batchTag($chatIds,$tags,$tag_info);

		return success('操作成功',$res);
	}
}